package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import Database.DBConnection;

/**
 * Servlet implementation class SingleNewProcedure
 */
public class SingleNewProcedure extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String category ="";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SingleNewProcedure() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String processName="";
		String code="";
		String procName="";

		String effectiveDateVar="";
		String reformattedStr = "";
		String serverPath = "";
		String filename="";
		
		try {
	        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	        for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();
	                if (fieldname.equalsIgnoreCase("PN")) {
	                	processName = fieldvalue;
	                } else if (fieldname.equalsIgnoreCase("Code")) {
	                	code = fieldvalue;
	                } else if (fieldname.equalsIgnoreCase("ProcedureName")) {
	                	procName = fieldvalue;
	                } else if (fieldname.equalsIgnoreCase("effectivedate")) {
	                	effectiveDateVar = fieldvalue;
	                	SimpleDateFormat odf = new SimpleDateFormat("dd MMM yy");
		        		SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
		        		try {		        			
		        			reformattedStr = sdf.format(odf.parse(effectiveDateVar));
		        		} catch (ParseException e) {
		        			// TODO Auto-generated catch block
		        			e.printStackTrace();
		        		}
		        		System.out.println(reformattedStr);
		        		int ret = insertRecordToDB(serverPath + filename, reformattedStr, processName, code, procName, category);
		    			System.out.println(ret + " records updated!");
	                }	        		
	            } else {
	                // Process form file field (input type="file").
	                String fieldname = item.getFieldName();
	                filename = FilenameUtils.getName(item.getName());
	                InputStream filecontent = item.getInputStream();	               
	                serverPath = getServerPath(processName);
	                String fullServerPath = request.getServletContext().getRealPath("/") + serverPath;
	                File filePath = new File(fullServerPath);
	    			System.out.println("Server folder path: " + fullServerPath);
	    			if (!filePath.exists()) {
	    				filePath.mkdirs();
	    			}
	    			int read = 0;
	    			FileOutputStream outputStream = new FileOutputStream(fullServerPath+filename);
	    			try {
		    			
		    			byte[] bytes = new byte[1024];
		    	 
		    			while ((read = filecontent.read(bytes)) != -1) {
		    				outputStream.write(bytes, 0, read);
		    			}
	    			} catch (Exception ex2) {
	    				System.out.println(ex2);
	    			} finally {
	    				if (outputStream!=null) {
	    					outputStream.flush();
	    					outputStream.close();
	    				}
	    				if (filecontent!=null) {
	    					filecontent.close();
	    				}
	    			}
	    			
	            }
	        }
	    } catch (FileUploadException e) {
	    	System.out.println(e);
	    	request.getRequestDispatcher("Proc_NewProcedure.jsp?result=-1").forward(request,response);	    	
	        //throw new ServletException("Cannot parse multipart request.", e);
	        
	    }
		System.out.println("Forwarding page...");
		request.getRequestDispatcher("Proc_NewProcedure.jsp?result=1").forward(request,response);
		
	}
	
	private String getServerPath(String processName) {
		Connection connection1st = null;
		Statement statement1st = null;
		ResultSet rs1st = null;
		String CodeVar="";
		try {

			connection1st = DBConnection.connect(true);
			statement1st = connection1st.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			String QueryString1st = "SELECT Category from qmsdb.processes WHERE ProcessName='"+processName+"'";
			rs1st = statement1st.executeQuery(QueryString1st);

			if (rs1st.next()) {
				category = rs1st.getString("Category");
				
			}

			// close all the connections.

		} catch (Exception ex) {
			System.out.println(ex);
		} finally {
			try {
				rs1st.close();			
				statement1st.close();
				connection1st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
		String serverPath = "WordDoc_Proccesses/" + category
				+ "/" + processName + "/Procedure/" + CodeVar + "/";
		System.out.println("Server folder path: " + serverPath);
		return serverPath;
	}
	
	private int insertRecordToDB (String fullFilePath, String dateUpdate, String processName, String code, String procedureName, String category) {
		Connection con = null;
		PreparedStatement stmt = null;
		String sql = "";
		int j1=0;
		con = DBConnection.connect(true);

		try {
			sql="INSERT INTO processes (ProcessName, Code, ProcedureName, ProcedureURL, ProcLastUpdate, Category) Values (?, ?, ?, ?, ?, ?)"; 
			stmt = con.prepareStatement(sql);
			stmt.setString(1, processName);
			stmt.setString(2, code);
			stmt.setString(3, procedureName);
			stmt.setString(4, fullFilePath);
			stmt.setString(5, dateUpdate);
			stmt.setString(6, category);
			j1=stmt.executeUpdate(); 
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return j1;
	}
}
